import axios from 'axios';
import qs from 'qs';
const SUCCESS_CODE = '0000';

const createAxios = (baseURL = '/api/', timeout = 60000) => {
  const service = axios.create({
    baseURL,
    timeout
  });

  service.defaults.withCredentials = true; // 让ajax携带cookie
  service.interceptors.request.use(
    // 每次请求都自动携带Cookie
    (config) => {
      if (config.isPostform) {
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
        config.data = qs.stringify(config.data);
      }
      config.headers.token = window.localStorage.getItem('token') || '';
      return config;
    },
    // eslint-disable-next-line handle-callback-err
    (error) => {
      return Promise.reject(error);
    }
  );

  service.interceptors.response.use(
    (rsp) => {
      if (rsp.data && rsp.data.code === SUCCESS_CODE) {
        return rsp.data.data;
      } else {
        return Promise.reject(rsp.data);
      }
    },
    // 拦截异常的响应
    (err) => {
      console.log('请求', err);
      switch (err.response.status) {
        case 401:
          break;
        case 403:
          break;
        case 500:
          break;
        case 404:
          break;
        default:
          return Promise.reject(err);
      }
      return Promise.reject(err);
    }
  );

  return service;
};

export default createAxios;

// export default service;
